﻿using System.Security.Authentication;
using MergeTool.ClassLib.Configuration;
using Microsoft.TeamFoundation.Client;
using System;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.VersionControl.Client;

namespace MergeTool.ClassLib.Common
{
    public class TfsConnection
    {
        private readonly Settings _settings;
        private TfsConfigurationServer _configurationServer;

        private static TfsConnection _instance;

        public static TfsConnection GetInstance()
        {
            if (_instance == null)
                _instance = new TfsConnection();

            if(!_instance.TryConnect())
                throw new AuthenticationException("Could not connect to TFS server!");

            return _instance;
        }

        private TfsConnection()
        {
            _settings = Settings.GetInstance();
        }

        private bool TryConnect()
        {
            try
            {
                this._configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(this._settings.ConnectionInfo.TFSUri);

                _configurationServer.EnsureAuthenticated();
            }
            catch (Exception ex)
            {

                throw ex;
            }

            return _configurationServer.HasAuthenticated;
        }

        public TfsConfigurationServer GeTfsConfigurationServer()
        {
            return this._configurationServer;
        }

        public TfsTeamProjectCollection GeTfsTeamProjectCollection()
        {
            TfsTeamProjectCollection ret;
            ret = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(this._settings.ConnectionInfo.GetTFSTeamProjectCollectionUri());

            return ret;
        }

        public VersionControlServer GetVersionControlServer()
        {
            return GetTeamProject().VersionControlServer;
        }

        public TeamProject GetTeamProject()
        {
            return this.GeTfsTeamProjectCollection()
                .GetService<VersionControlServer>()
                .GetTeamProject(this._settings.ConnectionInfo.TeamProject);
        }

    }
}
